<!DOCTYPE html>
<%@ page import="java.awt.*" %>
<%@ page import="java.util.Random" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page contentType="image/jpeg;charset=utf-8" language="java" %>
<%!
    //产生随机颜色方法
    public Color getColor(){
        Random random=new Random();
        int r=random.nextInt(256);
        int g=random.nextInt(256);
        int b=random.nextInt(256);
        return new Color(r,g,b);
    }

    //产生四位随机验证数字
    public String getNum(){
        int ran=(int)((Math.random()*9000)+1000);
        return String.valueOf(ran);
    }
%>

<%
    //禁止缓存 防止验证码不及时被加载
    response.setHeader("Pragma","no-cache");
    response.setHeader("Cache-Control","no-cache");
    response.setHeader("Expires","0");

    //绘制验证码
    BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);//宽 高 类型
    //画笔
    Graphics graphics=image.getGraphics();
    graphics.setFont(new Font("self",Font.BOLD,25));
    graphics.fillRect(0,0,80,30); //填充位置x y  填充宽高width height
    //绘制干扰线条 防止机器识别 起始x y  终止 x y
    for(int i=0;i<60;i++){
        Random random=new Random();
        int xBegin=random.nextInt(80);
        int yBegin=random.nextInt(30);
        int xEnd=random.nextInt(80);
        int yEnd=random.nextInt(30);
        graphics.setColor(getColor());
        //绘制线条
        graphics.drawLine(xBegin,yBegin,xEnd,yEnd);
    }
    //绘制验证码
    graphics.setColor(Color.BLACK);
    String checkCode=getNum();
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<checkCode.length();i++){
        sb.append(checkCode.charAt(i)+""); //验证码每一位数字
    }

    graphics.drawString(sb.toString(), 15,25);
    //将验证码存放到session 验证真实性
    session.setAttribute("CHECKCODE",checkCode);
    //真实产生图片
    ImageIO.write(image,"jpeg",response.getOutputStream());

    //关闭
    out.clear();
    out= pageContext.pushBody();//将自己写的图片放入表单 <input type="image" src="xxx"/>
%>
